# 1.定url：返回html页面，接收页面提交的数据并保存
# 2.一台电脑只能提交一次
from flask import Flask, render_template, request, session, redirect, url_for,jsonify
import os
from datetime import datetime
# template_folder=''表示当前目录为模板目录
# app = Flask(__name__,template_folder='')
app = Flask(__name__)
session = {}

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        # 根据ip判断是否已经提交过
        ip = request.remote_addr
        if ip not in session:
            # 将ip添加到session中
            session[ip] = True
            
            # 获取表单中的数据
            name = request.form['data']
            time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            # 将数据写入文件
            with open('data.txt', 'a') as f:
                f.write(f"{name}, {time}\n")
                
            return "Thank you for your submission!"
        else:
            return "You have already submitted."
        
    else:
        # 如果是GET请求，返回HTML表单
        return render_template('index.html')

if __name__ == '__main__':
    # app.template_folder=''表示当前目录为模板目录
    app.template_folder = ''
    app.run(debug=True)